package org.zxhtom.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.zxhtom.Exception.CommonException;
import org.zxhtom.adapter.PathAdapter;
import org.zxhtom.base.LicenseFactory;

/**
 * 
 * @ClassName: TransformOffice
 * @Description: 文档转换
 * @author zxhtom
 * @date 2018年1月29日
 */
public class TransformOffice {

	private Logger logger = LogManager.getLogger(TransformOffice.class);

	/**
	 * 
	 * @Description: 文档转换
	 * @param source
	 *            待转换的文档地址
	 * @param target
	 *            转换成新文档的地址
	 * @return boolean
	 * @throws
	 * @author zxhtom
	 * @date 2018年1月29日
	 */
	public boolean doTransform(String source, String target) {
		long old = System.currentTimeMillis();
		PathAdapter adapter = new PathAdapter();
		File file = new File(target);
		FileOutputStream outputStream;
		try {
			outputStream = new FileOutputStream(file);
			/** 根据原始路径初始化必要参数 */
			Class<?> classByPath = adapter.getClassByPath(source);
			/** 破解验证 */
			LicenseFactory.getInstance().isPassLicense(Class.forName(adapter.getLicensePath(source)));
			/** 实例对象开始转化 */
			Constructor<?> constructor = classByPath.getConstructor(String.class);
			constructor.setAccessible(true);
			Object instance = constructor.newInstance(source);
			/** 调用save方法 */
			Method method = classByPath.getMethod("save", OutputStream.class, int.class);
			/** 指定转换格式 */
			method.invoke(instance, outputStream, adapter.getFormatByPath(target));
			outputStream.close();
			long now = System.currentTimeMillis();
			logger.info("共耗时：" + ((now - old) / 1000.0) + "秒");
		} catch (FileNotFoundException e) {
			logger.error(e);
		} catch (ClassNotFoundException e) {
			logger.error(e);
		} catch (CommonException e) {
			logger.error(e);
		} catch (NoSuchMethodException e) {
			logger.error(e);
		} catch (SecurityException e) {
			logger.error(e);
		} catch (InstantiationException e) {
			logger.error(e);
		} catch (IllegalAccessException e) {
			logger.error(e);
		} catch (IllegalArgumentException e) {
			logger.error(e);
		} catch (InvocationTargetException e) {
			logger.error(e.getTargetException() + String.format(" : params (%1$s or %2$s) is not avalid ", source, target));
		} catch (IOException e) {
			logger.error(e);
		}
		return false;
	}
}
